package com.mrx.xcitools.utils;

import org.apache.maven.cli.MavenCli;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.function.Consumer;

/**
 * @author Mr.X
 * @since 2024-03-10 下午 4:20:27
 */
public class MavenUtils {

    private static final MavenCli mavenCli = new MavenCli();

    private static final Logger logger = LoggerFactory.getLogger(MavenUtils.class);

    public static boolean clean(String projectDir) {
        return doMaven(new String[]{"clean"}, projectDir);
    }

    public static boolean compile(String projectDir) {
        return doMaven(new String[]{"compile"}, projectDir);
    }

    public static boolean makePackage(String projectDir) {
        return doMaven(new String[]{"-Djansi.passthrough=true", "-DskipTests=true", "package"}, projectDir);
    }

    public static boolean makePackage(String projectDir, Consumer<String> logConsumer) {
        return doMaven(new String[]{"-Djansi.passthrough=true", "-DskipTests=true", "package"}, projectDir, logConsumer);
    }

    private static boolean doMaven(String[] args, String projectDir) {
        return doMaven(args, projectDir, it -> logger.debug("maven output: \n{}", it));
    }

    private static boolean doMaven(String[] args, String projectDir, Consumer<String> logConsumer) {
        System.setProperty("maven.multiModuleProjectDirectory", projectDir);
        ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
        PrintStream logStream = new PrintStream(resultStream);
        boolean result = mavenCli.doMain(args, projectDir, logStream, logStream) == 0;
        logConsumer.accept(resultStream.toString());
        return result;
    }

    public static void main(String[] args) {
        System.out.println(makePackage("D:\\工程\\Java\\x-ci-tools"));
    }

}
